import { defineStore } from "pinia";
import { Ref, readonly, ref } from "vue";
import { pinia } from "@/store/storeIndex";

export const useTagViewStore = defineStore("tagsView", () => {
    const visitedViews = ref<TypeTagViewI[]>([]);
    /**
     * 添加已访问视图到已访问视图列表中
     */
    function addVisitedView(view: TypeTagViewI) {
        console.log("addVisitedView", visitedViews, view);
        // 如果已经存在于已访问的视图列表中，则不再添加
        if (visitedViews.value.some((v) => v.fullPath === view.fullPath)) {
            return;
        }
        // 如果视图是固定的（affix），则在已访问的视图列表的开头添加
        if (view.affix) {
            visitedViews.value.unshift(view);
        } else {
            // 如果视图不是固定的，则在已访问的视图列表的末尾添加
            visitedViews.value.push(view);
        }
    }

    /**
     * 从已访问视图列表中删除指定的视图
     */
    function delVisitedView(tag: TypeTagViewI) {
        return new Promise<void>((resolve,reject) => {
            const index=visitedViews.value.indexOf(tag);
            if(index !== -1){
                visitedViews.value.splice(index,1);
                resolve();
            }else{
                reject()
            }
        });
    }

    function delOtherVisitedViews(tag: TypeTagViewI) {
          visitedViews.value = visitedViews.value.filter((v) => {
            return v?.affix || v.fullPath === tag.fullPath;
          });
    }

    function delLeftViews(view: TypeTagViewI) {
          const currIndex = visitedViews.value.findIndex(
            (v) => v.fullPath === view.fullPath
          );
          if (currIndex === -1) {
            return;
          }
          visitedViews.value = visitedViews.value.filter((item, index) => {
            if (index >= currIndex || item?.affix) {
              return true;
            }
            return false;
          });
        }

      function delRightViews(view: TypeTagViewI) {
          const currIndex = visitedViews.value.findIndex(
            (v) => v.fullPath === view.fullPath
          );
          console.log('currIndex',currIndex);
          if (currIndex === -1) {
            return;
          }
          
          visitedViews.value = visitedViews.value.filter((item, index) => {
            if (index <= currIndex || item?.affix) {
              return true;
            }
          });
        //   console.log('visitedViews.value',JSON.stringify(visitedViews.value));

      }

      function delAllViews() {
          const affixTags = visitedViews.value.filter((tag) => tag?.affix);
          visitedViews.value = affixTags;
      }

      function delOtherViews(view: TypeTagViewI) {
          delOtherVisitedViews(view);
      }

    return {
        visitedViews: visitedViews as Ref<readonly TypeTagViewI[]>,
        addVisitedView,
        delVisitedView,
        delOtherVisitedViews,
        delLeftViews,
        delRightViews,
        delAllViews,
        delOtherViews       
    };
});

export function useTagViewStoreWithSetup() {
    return useTagViewStore(pinia);
}
